import 'package:shared_preferences/shared_preferences.dart';

/**
 * @Description: sp 工具类
 * @Author: 下雨了
 * @CreateDate: 2021-12-02 15:26
 * @UpdateUser: 下雨了
 * @UpdateDate:  2021-12-02 15:26
 * @UpdateRemark: 优化代码结构
 * @Version: 1.1
 */
///
//
// dependencies:
//   shared_preferences: ^2.0.9
//

//定义一个top-level（全局）变量，页面引入该文件后可以直接使用 logUtils
final sp = SPUtils();

class SPUtils {
  // 私有构造函数
  SPUtils._internal();

  // 保存单例
  static final SPUtils _spUtils = SPUtils._internal();

  // 工厂构造函数
  factory SPUtils() => _spUtils;


  Future<SharedPreferences> getInstance() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    return sp;
  }

  /// 保存数据
  Future<bool> setString(String key, String value) async {
    // return await getInstance().then((value1) => value1.setString(key, value));
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    return sharedPreferences.setString(key, value);
  }

  /// 获取数据
  Future<String?> getString(String key) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    return sharedPreferences.getString(key);
  }

  /// 保存数据
  Future<bool> setBool(String key, bool value) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    return sharedPreferences.setBool(key, value);
  }

  /// 获取数据
  Future<bool?> getBool(String key) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    return sharedPreferences.getBool(key);
  }

  /// 移除 指定key数据
  Future<bool> remove(String key) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    return sharedPreferences.remove(key);
  }

  /// 检测数据是否存在
  Future<bool> contains(String key) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    return sharedPreferences.containsKey(key);
  }

  /// 清除
  Future<bool> clear() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    return sharedPreferences.clear();
  }

  /// 重新加载
  Future<void> reload() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.reload();
  }
}
